<?php

class SeoRouting extends CActiveRecord
{
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	public function tableName()
	{
		return '{{seo_routing}}';
	}

	public function createAlias($rule, $params, $urlSuffix, $defaultUrl, $escapeSymbols)
	{
		$sql = "SELECT alias FROM ".$this->tableName()." WHERE (url=:url AND language=:language)";
		$command = Yii::app()->db->createCommand($sql);
		$command->bindParam(':url', $defaultUrl);
		$command->bindParam(':language', Yii::app()->language);
		$result = $command->queryRow();

		if ($result)
		{
			return $result['alias']!=='' ? $result['alias'].$urlSuffix : $result['alias'];
		}
		else
		{
			//transalate
			$route = explode('/', $rule['template']);
			foreach ($route as &$r)
			{
				Yii::import($rule['path']);
				$model = new $rule['model'];
				if (preg_match('/^\<([\w]*)\>$/', $r, $matches))
				{
					if (isset($params[$matches[1]]))
					{
						$r = $params[$matches[1]];
					}
					else
					{
						/*
						 *  @todo if PrimaryKey is not ID
						 */
						$object = $model->findByPk($params['id']);
						if (isset($object->{$matches[1].'_'.Yii::app()->language}) && !empty($object->{$matches[1].'_'.Yii::app()->language}))
						{
							$r = $object->{$matches[1].'_'.Yii::app()->language};
						}
					}
				}
				
				$r = str_replace($escapeSymbols, '', $r);
				$r = urlencode(Yii::t($rule['model'].'Module.seo', $r, array(), null, Yii::app()->language));
			}
			$alias = implode('/', $route);

			/* check if unique*/
			$regexpr = '^'.str_replace('+', '[+]', $alias).'(_[[:digit:]]+)*$';
			$sql = "SELECT MAX(CAST(REPLACE(alias, :faq, :replace) AS UNSIGNED)) AS counter FROM ".$this->tableName()." WHERE alias REGEXP :regexpr";
			$command = Yii::app()->db->createCommand($sql);
			$command->bindParam(':regexpr', $regexpr);
			$command->bindValue(':faq', $alias.'_');
			$command->bindValue(':replace', '');
			$result = $command->queryRow();

			if (!is_null($result['counter']))
			{
				$counter = (int)$result['counter'];
				$alias .= '_'.++$counter;
			}
			/* check if unique*/
		
			
			$sql = "INSERT INTO {{seo_routing}} (alias, url, language) VALUES (:alias, :url, :language)";
			$command = Yii::app()->db->createCommand($sql);
			$command->bindParam(':alias', $alias);
			$command->bindParam(':url', $defaultUrl);
			$command->bindParam(':language', Yii::app()->language);
			$command->execute();

			// add suffix
			return $alias!=='' ? $alias.$urlSuffix : $alias;
		}
	}

	public function getUrlByAlias($alias)
	{
		$sql = "SELECT url FROM ".$this->tableName()." WHERE alias=:alias";
		$command = Yii::app()->db->createCommand($sql);
		$command->bindParam(':alias', $alias);
		$result = $command->queryRow();
		
		if ($result['url']){
			return $result['url'];
		}

		return false;
	}

	public function truncateTable() {
		return Yii::app()->db->createCommand()->truncateTable($this->tableName());
	}
}